<?php
namespace app\admin\controller;
use think\Controller;


/**
 * 后台基础类库
 */
class Base extends Controller
{
	/**
	 * [$page 第几页]
	 * @var string
	 */
	public $page = '';
	/**
	 * [$size 每页多少条]
	 * @var string
	 */
	public $size = '';
	/**
	 * [$from 查寻条件的起始值]
	 * @var integer
	 */
	public $from = 0;

	/**
	 * [$model 模型]
	 * @var string
	 */
	public $model = '';

	/**
	 * [_initialize 初始化方法]
	 * @return [type] [description]
	 */
	public function _initialize(){
		//判断用户是否登录
		$isLogin = $this->isLogin();
		if (!$isLogin) {
			return $this->redirect("login/login");
		}
	}

	public function isLogin(){
		//获取session
		$user = session(config('admin.session_user'),'',config('admin.session_user_scope'));
		if ($user && $user->id) {
			return true;
		}

		return false;
	}

	/**
	 * [getPageAndSize 获取分页page size值]
	 * @return [type] [description]
	 */
	public function getPageAndSize($data){
		$this->page = !empty($data['page'])?$data['page']:1;//当前页
		$this->size = !empty($data['size'])?$data['size']:config('paginate.list_rows');
		$this->form = ($this->page-1)*$this->size;
	}

	/**
	 *通用删除逻辑
	 */
	public function delete($id = 0){
		if (!intval($id)) {
			return $this->result('',0,'Id不合法');
		}


		//如果表名和控制器文件名一样
		$model = $this->model?$this->model:request()->controller();
		//如果php是php7 $model = $this->model??request()->controller();



		try {
			$res = model($model)->save(['status'=>-1],['id'=>$id]);
		} catch (\Exception $e) {
			return $this->result('',0,$e->getMessage());
		}

		if ($res) {
			return $this->result(['jump_url'=>$_SERVER['HTTP_REFERER']],1,'OK');
		}

		return $this->result('',0,'删除失败');
	}

	    /**
     * 通用化修改状态
     */
    public function status() {
        $data  = input('param.');
        // tp5  validate 机制 校验  小伙伴自行完成 id status

        // 通过id 去库中查询下记录是否存在
        //model('News')->get($data['id']);

        $model = $this->model ? $this->model : request()->controller();

        try {
            $res = model($model)->save(['status' => $data['status']], ['id' => $data['id']]);
        }catch(\Exception $e) {
            return $this->result('', 0, $e->getMessage());
        }

        if($res) {
            return $this->result(['jump_url' => $_SERVER['HTTP_REFERER']], 1, 'OK');
        }
        return $this->result('', 0, '修改失败');
    }
}
